package cn.cnhis.online.activity.login.view;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.xuexiang.xui.widget.progress.loading.ARCLoadingView;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.cnhis.online.BuildConfig;
import cn.cnhis.online.R;
import cn.cnhis.online.activity.agreement.view.AgreementActivity;
import cn.cnhis.online.activity.forgotpassword.view.ForgotPasswordActivity;
import cn.cnhis.online.activity.login.contract.ILoginContract;
import cn.cnhis.online.activity.login.presenter.LoginPresenter;
import cn.cnhis.online.activity.main.view.MainActivity;
import cn.cnhis.online.base.ActivityStack;
import cn.cnhis.online.base.BaseMvpActivity;
import cn.cnhis.online.mymodule.Constants;
import cn.cnhis.online.mymodule.Utils.AndroidBugWorkaround;
import cn.cnhis.online.mymodule.Utils.EquipmentInfoCollection;
import cn.cnhis.online.mymodule.Utils.EquipmentPO;
import cn.cnhis.online.mymodule.Utils.KeyBoardHelperUtil;
import cn.cnhis.online.mymodule.Utils.NotificationsUtils;
import cn.cnhis.online.mymodule.sp.MySpUtils;
import okhttp3.ResponseBody;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;


@RuntimePermissions
public class LoginActivity extends BaseMvpActivity<ILoginContract.View, ILoginContract.Presenter> implements ILoginContract.View, KeyBoardHelperUtil.OnKeyBoardStatusChangeListener {

    @BindView(R.id.edit_user)
    EditText editUser;
    @BindView(R.id.edit_password)
    EditText editPassword;
    @BindView(R.id.img_agreement)
    ImageView imgAgreement;
    @BindView(R.id.txt_agreement)
    TextView txtAgreement;
    @BindView(R.id.txt_forgot_password)
    TextView txtForgotPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.img_code)
    ImageView imgCode;
    @BindView(R.id.img_login_logo)
    ImageView imgLoginLogo;
    @BindView(R.id.layout_code)
    LinearLayout layoutCode;
    @BindView(R.id.img_clear)
    ImageView imgClear;
    @BindView(R.id.img_show_password)
    ImageView imgShowPassword;
    @BindView(R.id.txt_hospital_name)
    TextView txtHospitalName;
    @BindView(R.id.arc_loading)
    ARCLoadingView arcLoading;
    @BindView(R.id.txt_user_title)
    TextView txtUserTitle;
    @BindView(R.id.txt_password_title)
    TextView txtPasswordTitle;
    @BindView(R.id.txt_code_title)
    TextView txtCodeTitle;
    @BindView(R.id.layout_parent)
    FrameLayout frameLayout;
    @BindView(R.id.bottom_view)
    View bottomView;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    @BindView(R.id.layout_agreement)
    LinearLayout layoutAgreement;

    private SharedPreferences sharedPreferences;

    /*登录失败次数统计 超过三次 需要输入验证码*/
    private int loginCount = 0;


    private int bottomHeight;
    private KeyBoardHelperUtil boardHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityStack.getInstance().pushActivity(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        setContentView(R.layout.activity_login);
        boardHelper = new KeyBoardHelperUtil(this);
        boardHelper.onCreate();
        boardHelper.setOnKeyBoardStatusChangeListener(this);

    }


    @Override
    public void onContentChanged() {
        super.onContentChanged();
//        AndroidBugWorkaround.assistActivity(this);
        getPresenter().getLogo();
        LoginActivityPermissionsDispatcher.needPermissionWithPermissionCheck(this);
        checkStatus();
        checkLoginErr();
        checkAgreement(MySpUtils.getAgreementStatus(this));
        textChange();
        getPresenter().getCode();
        getPresenter().getAppActiveMqInfo();
        checkOff(this);

//        getPresenter().getMenuShowColor();

    }

    private void textChange() {
        editUser.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (editUser.getText().toString().length() > 0) {
                    txtUserTitle.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editUser.getText().toString().length() > 0) {
                    txtUserTitle.setVisibility(View.VISIBLE);
                    editUser.setBackground(getResources().getDrawable(R.drawable.border_active));
                } else {
                    editUser.setBackground(getResources().getDrawable(R.drawable.border_normal));
                }

                checkAgreement(MySpUtils.getAgreementStatus(LoginActivity.this));
            }
        });
        editPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (editPassword.getText().toString().length() > 0) {
                    txtPasswordTitle.setVisibility(View.VISIBLE);
                }

                checkAgreement(MySpUtils.getAgreementStatus(LoginActivity.this));
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editPassword.getText().toString().length() > 0) {
                    txtPasswordTitle.setVisibility(View.VISIBLE);
                    editPassword.setBackground(getResources().getDrawable(R.drawable.border_active));
                } else {
                    editPassword.setBackground(getResources().getDrawable(R.drawable.border_normal));
                }
                checkAgreement(MySpUtils.getAgreementStatus(LoginActivity.this));
            }
        });

        editCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (editCode.getText().toString().length() > 0) {
                    txtCodeTitle.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editCode.getText().toString().length() > 0) {
                    txtCodeTitle.setVisibility(View.VISIBLE);
                    editCode.setBackground(getResources().getDrawable(R.drawable.border_active));
                } else {
                    editCode.setBackground(getResources().getDrawable(R.drawable.border_normal));
                }
            }
        });

    }

    private void checkLoginErr() {
        Integer loginErrorCount = MySpUtils.getLoginErrorCount(this);
        if (BuildConfig.DEBUG) Log.d("LoginActivity", "loginErrorCount:" + loginErrorCount);
        if (loginErrorCount >= 3) {
            layoutCode.setVisibility(View.VISIBLE);
        }
    }


    public void checkStatus() {
        if (editUser.getText().length() > 0) {
            imgClear.setVisibility(View.VISIBLE);
        } else {
            imgClear.setVisibility(View.INVISIBLE);
        }
        if (editPassword.getText().length() > 0) {
            imgShowPassword.setVisibility(View.VISIBLE);
        } else {
            imgShowPassword.setVisibility(View.INVISIBLE);
        }

        editUser.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editUser.getText().length() > 0) {
                    imgClear.setVisibility(View.VISIBLE);
                } else {
                    imgClear.setVisibility(View.INVISIBLE);
                }


            }
        });
        editPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editPassword.getText().length() > 0) {
                    imgShowPassword.setVisibility(View.VISIBLE);
                } else {
                    imgShowPassword.setVisibility(View.INVISIBLE);
                }
            }
        });


    }

    private void checkAgreement(boolean status) {
        if (BuildConfig.DEBUG) Log.d("LoginActivity", "status:" + status);


        if (status) {
            imgAgreement.setImageResource(R.drawable.radio_active);
        } else {
            imgAgreement.setImageResource(R.drawable.radio_normal);
        }

        if (layoutCode.getVisibility() == View.VISIBLE) {
            if (status && editUser.getText().length() > 0 && editPassword.getText().length() > 0 && editCode.getText().length() > 0) {
                btnLogin.setBackground(getResources().getDrawable(R.mipmap.btn_active));
            } else {
                btnLogin.setBackground(getResources().getDrawable(R.mipmap.btn_normal));
            }

        } else {
            if (status && editUser.getText().length() > 0 && editPassword.getText().length() > 0) {
                btnLogin.setBackground(getResources().getDrawable(R.mipmap.btn_active));
            } else {
                btnLogin.setBackground(getResources().getDrawable(R.mipmap.btn_normal));
            }
        }

//        if (status && editUser.getText().length() > 0 && editPassword.getText().length() > 0 && editPassword.getText().length() > 0) {
//            imgAgreement.setImageResource(R.drawable.radio_active);
//            btnLogin.setBackgroundColor(getResources().getColor(R.color.login_active));
//        } else {
//            imgAgreement.setImageResource(R.drawable.radio_normal);
//            btnLogin.setBackgroundColor(getResources().getColor(R.color.login_default));
//        }
        MySpUtils.setAgreementStatus(this, status);
    }

    private boolean showPassword;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.layout_agreement, R.id.txt_agreement, R.id.txt_forgot_password, R.id.btn_login, R.id.img_code, R.id.img_clear, R.id.img_show_password, R.id.img_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_agreement:
            case R.id.layout_agreement:
                boolean agreementStatus = MySpUtils.getAgreementStatus(this);
                if (agreementStatus) {
                    checkAgreement(false);
                } else {
                    checkAgreement(true);
                }

                break;
            case R.id.txt_agreement:
//                checkAgreement(!rbAgreement.isChecked());
                startOterActivity(this, AgreementActivity.class);
                break;
            case R.id.txt_forgot_password:
                startOterActivity(this, ForgotPasswordActivity.class);
                break;
            case R.id.img_code:
                getPresenter().getCode();
                break;
            case R.id.img_clear:
                editUser.setText("");
                imgClear.setVisibility(View.INVISIBLE);
                break;
            case R.id.img_show_password:
//                editPassword.setInputType(editPassword.getInputType() == InputType.TYPE_CLASS_TEXT ? InputType.TYPE_TEXT_VARIATION_PASSWORD : InputType.TYPE_CLASS_TEXT);
//                editPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD );
                if (showPassword) {// 显示密码
                    imgShowPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_visibility_black_24dp));
                    editPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    editPassword.setSelection(editPassword.getText().toString().length());
                    showPassword = !showPassword;
                } else {// 隐藏密码
                    imgShowPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_visibility_off_black_24dp));
                    editPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    editPassword.setSelection(editPassword.getText().toString().length());
                    showPassword = !showPassword;
                }
                break;
            case R.id.btn_login:

                if (!MySpUtils.getAgreementStatus(this)) {
                    Toast.makeText(this, "请先阅读并勾选用户协议！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map map = getMap();
                if (map != null) {
                    arcLoading.setVisibility(View.VISIBLE);
                    arcLoading.start();
                    getPresenter().login(map);
                }
                break;
        }
    }

    @TargetApi(Build.VERSION_CODES.N)
    @RequiresApi(api = Build.VERSION_CODES.N)
    private Map getMap() {
        String userName = editUser.getText().toString();
        String password = editPassword.getText().toString();
        String code = editPassword.getText().toString();

        if (TextUtils.isEmpty(userName)) {
            Toast.makeText(this, "用户名不得为空！", Toast.LENGTH_SHORT).show();
            return null;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码不得为空！", Toast.LENGTH_SHORT).show();
            return null;
        }
        if (TextUtils.isEmpty(code) && layoutCode.getVisibility() == View.VISIBLE) {
            Toast.makeText(this, "验证码不得为空！", Toast.LENGTH_SHORT).show();
            return null;
        }

        Map map = new HashMap();
        map.put("loginName", userName);
        map.put("password", password);
        if (layoutCode.getVisibility() == View.VISIBLE) {
            map.put("code", code);
        }
        EquipmentInfoCollection equipmentInfoCollection = new EquipmentInfoCollection();
        EquipmentPO equipmentInfo = equipmentInfoCollection.getEquipmentInfo(this);
        map.put("equipmentInfo", getGson().toJson(equipmentInfo));
        map.put("openId", "");

        return map;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void showErr(String e) {
        Toast.makeText(this, e, Toast.LENGTH_SHORT).show();
        if (arcLoading.isStart()) {
            arcLoading.stop();
            arcLoading.setVisibility(View.INVISIBLE);
        }
    }


    @Override
    public void login(Map map) {
        try {

            arcLoading.stop();
            arcLoading.setVisibility(View.INVISIBLE);
            JSONObject jsonObject = toJSONObject(map);
            if (BuildConfig.DEBUG) Log.d("LoginActivity", "map:" + jsonObject);

            if (jsonObject.getString("result").equals(Constants.SUCCESS)) {
                Toast.makeText(this, "登录成功！", Toast.LENGTH_SHORT).show();
                MySpUtils.setLoginStatus(this, true);
                MySpUtils.setUserInfo(this, jsonObject.get("map").toString());
                MySpUtils.setLoginErrorCount(this, 0);
                MySpUtils.setSysLoginSessionId(this, "" + jsonObject.getJSONObject("map").getString("sysLoginSessionId"));
                startOterActivity(this, MainActivity.class);
                finish();
            } else if (jsonObject.getString("result").equals(Constants.Failure)) {
                loginCount++;
                Toast.makeText(this, jsonObject.getString(Constants.RESULTMSG), Toast.LENGTH_SHORT).show();
//                loginCount = jsonObject.getJSONObject("map").getInt("loginFailCount");
                if (loginCount >= 3) {
                    MySpUtils.setLoginErrorCount(this, loginCount);
                    layoutCode.setVisibility(View.VISIBLE);
                } else {
                    layoutCode.setVisibility(View.GONE);
                }
            } else {
                if (jsonObject.getString("result").equals(Constants.NO_LOGIN)) {
                    Toast.makeText(this, "免密校验失败", Toast.LENGTH_SHORT).show();
                }

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void getLogo(Map logo) {
        Log.d("LoginActivity", "logo:" + logo);
        if (logo != null) {
            JSONObject jsonObject = toJSONObject(logo);
            try {
                if (jsonObject.getString(Constants.RESULT).equals(Constants.SUCCESS)) {

                    String logoUrl = "" + jsonObject.getJSONObject("map").get("login_logo");
                    String name = "" + jsonObject.getJSONObject("map").get("platform_title");
                    if (name != null) {
                        txtHospitalName.setText(name);
                    }
                    if (!"".equals(logoUrl)) {
                        if (!isDestroyed())
                            Glide.with(LoginActivity.this).asBitmap().diskCacheStrategy(DiskCacheStrategy.RESOURCE).load(logoUrl).into(imgLoginLogo);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void getCode(ResponseBody map) {
        if (map != null && map.byteStream() != null) {
            Bitmap bitmap = BitmapFactory.decodeStream(map.byteStream());
            imgCode.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this, "获取验证码为空，请联系工程师！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getMenuShowColor(Map map) {
        Log.d("LoginActivity", "map:" + map);
        if (map != null) {
            JSONObject jsonObject = toJSONObject(map);
            try {
                if (jsonObject.getString(Constants.RESULT).equals(Constants.SUCCESS)) {
                    MySpUtils.setThemeColor(this, jsonObject.toString());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void getAppActiveMqInfo(Map map) {
        if (BuildConfig.DEBUG) Log.d("LoginActivity", "getAppActiveMqInfo:" + map);
        JSONObject jsonObject = toJSONObject(map);
        try {
            if (jsonObject.getString(Constants.RESULT).equals(Constants.SUCCESS)) {
                String json = jsonObject.getJSONObject(Constants.MAP).toString();
                if (!isDestroyed()) {
                    MySpUtils.setMQINFO(this, json);
                }

            } else if (jsonObject.getString(Constants.RESULT).equals(Constants.Failure)) {
                Toast.makeText(this, "获取MQ信息失败！", Toast.LENGTH_SHORT).show();
            } else if (jsonObject.getString(Constants.RESULT).equals(Constants.NO_LOGIN)) {
                Toast.makeText(this, "免密校验失败！", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public ILoginContract.Presenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    public ILoginContract.View createView() {
        return this;
    }


    @NeedsPermission({Manifest.permission.ACCESS_NOTIFICATION_POLICY, Manifest.permission.CALL_PHONE, Manifest.permission.WAKE_LOCK, Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.REQUEST_INSTALL_PACKAGES})
    void needPermission() {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    @Override
    public void OnKeyBoardPop(int keyBoardheight) {

        scrollView.scrollBy(0, keyBoardheight);
        bottomHeight = keyBoardheight;

//        int height = keyBoardheight;
//        if (BuildConfig.DEBUG) Log.d("LoginActivity", "height:111" + height);
//        ViewGroup.LayoutParams layoutParams = bottomView.getLayoutParams();
//        layoutParams.height = height;
//        bottomView.setLayoutParams(layoutParams);
//        scrollView.smoothScrollBy(0, height);
//        int visibility = bottomView.getVisibility();
//        if (visibility == View.VISIBLE) {
//            bottomView.setVisibility(View.GONE);
//            bottomView.setVisibility(View.VISIBLE);
//        } else {
//            bottomView.setVisibility(View.VISIBLE);
//            bottomView.setVisibility(View.GONE);
//        }

        if (BuildConfig.DEBUG)
            Log.d("LoginActivity", "bottomView.getVisibility():111" + bottomView.getVisibility());
    }

    @Override
    public void OnKeyBoardClose(int oldKeyBoardheight) {
//         bottomView.setVisibility(View.GONE);
        scrollView.smoothScrollBy(0, -bottomHeight);
//        ViewGroup.LayoutParams layoutParams = bottomView.getLayoutParams();
//        layoutParams.height = 100;
//        bottomView.setLayoutParams(layoutParams);


    }


    public void checkOff(Context context) {
        if (!NotificationsUtils.isNotificationEnabled(context)) {
            final AlertDialog dialog = new AlertDialog.Builder(context).create();
            dialog.show();

            View view = View.inflate(this, R.layout.dialog_notice, null);
            dialog.setContentView(view);
            TextView ct = (TextView) view.findViewById(R.id.txt_content);
            ct.setText("检测到您没有打开通知权限，是否去打开");
            TextView confirm = (TextView) view.findViewById(R.id.txt_yes);
            confirm.setText("确定");
            confirm.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dialog.cancel();
                    Intent localIntent = new Intent();
                    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (Build.VERSION.SDK_INT >= 9) {
                        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                        localIntent.setData(Uri.fromParts("package", LoginActivity.this.getPackageName(), null));
                    } else if (Build.VERSION.SDK_INT <= 8) {
                        localIntent.setAction(Intent.ACTION_VIEW);

                        localIntent.setClassName("com.android.settings",
                                "com.android.settings.InstalledAppDetails");

                        localIntent.putExtra("com.android.settings.ApplicationPkgName",
                                LoginActivity.this.getPackageName());
                    }
                    startActivity(localIntent);
                }
            });

            TextView cancel = (TextView) view.findViewById(R.id.txt_no);
            cancel.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dialog.cancel();
                }
            });
        }
    }

}
